<template>
  <div>
    <div class="index-box">
      <div class="content-head">
        <div class="content-head-title">
          <a-button type="primary" icon="plus" style="margin-right: 8px;" @click="() => { labelsModalPop = true;labelsModalTitle = '添加标签'; }">添加</a-button>
        </div>
        <div class="content-head-extra">
          <a-select style="width:200px;margin-right: 16px;" :options="typeNameList" @change="onSearch($event,1)" placeholder="请选择标签分类" />
          <a-input-search style="width:300px;" placeholder="请输入标签名称" enterButton @search="onSearch($event,2)"/>
        </div>
      </div>
      <div class="content-body">
        <s-table ref="table" :columns="columns" :data="dataSource" :loading="loading" rowKey="id" >
          <template slot="operation" slot-scope="text,record">
            <a-dropdown>
              <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
              <a-menu slot="overlay" @click="operation($event,record)">
                <a-menu-item key="1">编辑</a-menu-item>
                <a-menu-item key="2">绑定{{typeNameText[record['type_name']]}}</a-menu-item>
                <a-menu-item key="2.5">查看列表</a-menu-item>
                <a-menu-item key="3">删除</a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </s-table>
      </div>
    </div>
    <!-- 添加or编辑标签 -->
    <a-modal :title="labelsModalTitle" destroyOnClose v-model="labelsModalPop" :width="600" @ok="submitLabels" :confirmLoading="labelsOperationLoading">
      <a-form :form="labelsForm">
        <a-form-item label="标签名称" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
          <a-input placeholder="请输入标签名称" v-decorator="['name',{rules:[{required:true,message:'标签名称不可为空'}]}]" />
        </a-form-item>
        <a-form-item label="标签分类" :labelCol="{xs:{span:24},sm:{span:7}}" :wrapperCol="{xs:{span:24},sm:{span:15}}">
          <a-select placeholder="请选择标签分类" :options="[{label:'房屋标签',value:1},{label:'车位标签',value:2},{label:'车辆标签',value:3},{label:'住户标签',value:4}]" :disabled="labelsModalTitle === '编辑标签'" v-decorator="['type_name',{rules:[{required:true,message:'请选择标签分类'}]}]" />
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['id']" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 绑定房屋or车位or车辆标签 -->
    <a-drawer destroyOnClose :title="bindTitle" :visible="bindPop" @close="() => { bindPop = false; }" :width="350" :wrapStyle="{height: 'calc(100% - 108px)',overflow: 'auto',paddingBottom: '108px'}">
      <a-skeleton active :loading="bindDataLoading">
        <a-tree style="padding-bottom:55px" checkable :treeData="bindDataList" treeCheckable v-model="bingdIds"/>
      </a-skeleton>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <a-button :style="{marginRight: '8px'}" @click="() => { bindPop = false; }">
          取消
        </a-button>
        <a-button :loading="submitLabelsHorpLoading" :disabled="submitLabelsHorpLoading" @click="submitLabelsHorp" type="primary">提交</a-button>
      </div>
    </a-drawer>
    <!-- 绑定住户标签 -->
    <a-modal :title="bindHouseTitle" destroyOnClose v-model="bindUserModal" :confirmLoading="bindUserModalLoading" @ok="bindUserSubmit">
      <a-form :form="bindUserForm" @submit="bindUserSubmit">
        <a-form-item label="所属小区" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-select placeholder="请选择所属小区" :options="communityList" v-decorator="['bd_info_id',{rules:[{required:true,message:'请选择所属小区'}],initialValue:undefined}]" />
        </a-form-item>
        <a-form-item label="选择住户" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-select placeholder="输入手机号选择住户，可多选" @search="getBindUserList" :notFoundContent="fetching ? undefined : '无匹配结果'" allowClear optionFilterProp="children" mode="multiple" v-decorator="['house_user_id',{rules:[{required:true,message:'请选择住户'}],initialValue:[]}]" >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in bindUserList" :key="item.value">{{item.label}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['id',{rules:[{required:true,message:'标签id不可为空'}],initialValue:''}]" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import {STable} from '@/components'
  export default {
    name: 'data_labels_index',
    data() {
      return {
        token:this.$ls.get(ACCESS_TOKEN),
        description:'数据标签可用于对房屋、车位、车辆、住户进行自由分组',
        typeNameList:[{label:'全部标签',value:0},{label:'房屋标签',value:1},{label:'车位标签',value:2},{label:'车辆标签',value:3},{label:'住户标签',value:4}],
        typeNameText:{"1":'房屋',"2":'车位',"3":'车辆',"4":'住户'},
        columns:[{title:'编号',dataIndex:'id'},{ title:'标签名称',dataIndex:'name' }, { title: '分类',dataIndex:'type_name_text' }, { title: '操作',dataIndex:'operation', scopedSlots:{customRender:'operation'} }],
        loading:false,
        queryParam:{},
        dataSource:parameter => {
          return this.getList(Object.assign(parameter, this.queryParam))
            .then(res => {
              return res
            })
        }, // 列数据
        bingdIds:[],
        labelsInfo:{}, // 标签信息
        labelsForm:this.$form.createForm(this),
        labelsModalTitle:'', // 添加or编辑标签弹窗文字
        labelsModalPop:false, // 添加or编辑标签弹窗
        labelsOperationLoading:false, // 添加or编辑标题弹窗确定按钮加载状态
        bindTitle:'', // 绑定标签标题
        bindPop:false, // 绑定标签弹窗
        bindDataLoading:true, // 绑定标签骨架屏加载状态
        bindForm:this.$form.createForm(this),
        bindDataList:[],
        hasBind:[], // 已绑定住户
        submitLabelsHorpLoading:false,
        bindUserForm:this.$form.createForm(this), // 绑定住户
        bindUserModal:false, // 绑定住户
        bindUserModalLoading:false, // 绑定住户loading
        fetching:false,
        communityList:[], // 小区列表
        bindUserList:[], // 住户列表
        bindHouseTitle: '绑定住户', // 绑定住户title
      }
    },
    components:{STable},
    mounted() {
      this.getCommunity();
    },
    methods:{
      getList(param) {
        this.loading = true;
        return new Promise((resolve, reject) => {
          this.axios({
            method:'post',
            url:'/labels/getList',
            data:Object.assign(param,{token:this.token})
          }).then(res => {
            resolve(res.data);
          }).catch(err => {
            this.$message.error('服务器发生错误...',2);
          }).finally(() => {
            this.loading = false;
          })
        })
      },
      // 筛选
      onSearch(val,type) {
        if(type == 1) this.queryParam['type_name'] = val;
        else this.queryParam['name'] = val;
        this.$refs.table.refresh(true);
      },
      // 添加or编辑标签
      submitLabels(e) {
        e.preventDefault();
        this.labelsForm.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          Object.assign(values,{token:this.token});
          this.labelsOperationLoading = true;
          this.axios({
            method: 'post',
            url: '/labels/operation',
            data: values
          }).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg, 1);
              this.labelsModalPop = false;
              this.labelsModalTitle = '';
              this.$refs.table.refresh();
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2), this.spinning = false
          }).finally(() => {
            this.labelsOperationLoading = false
          })
        })
      },
      submitLabelsHorp(){
        this.submitLabelsHorpLoading = true;
        let ids = [];
        for(let item of this.bingdIds) {
          if(item.includes('fw_')) ids.push(item.replace('fw_',''));
          if(item.includes('cl_')) ids.push(item.replace('cl_',''));
          if(item.includes('cw_')) ids.push(item.replace('cw_',''));
        }
        let has = this.hasBind.map(item => {
          if(item.includes('fw_')) return item.replace('fw_','');
          if(item.includes('cl_')) return item.replace('cl_','');
          if(item.includes('cw_')) return item.replace('cw_','');
        })
        this.axios({
          method:'post',
          url:'/labels/horpBindLabels',
          data:{token:this.token,id:this.labelsInfo.id,ids,has}
        }).then(res => {
          if(res.code === 0){
            this.$message.success(res.msg, 1);
            this.bindPop = false;
          }else this.$message.warn(res.msg,2);
        }).catch(err => {
          this.$message.error('服务器发生错误...',2);
        }).finally(() => {
          this.submitLabelsHorpLoading = false;
        });
      },
      // 标签数据操作
      operation({ key },info) {
        const _this = this;
        _this.labelsInfo = info;
        // 编辑
        if(key === '1') {
          _this.labelsModalTitle = '编辑标签';
          _this.labelsModalPop = true;
          _this.$nextTick(() => {
            _this.labelsForm.setFieldsValue({id:info.id,name:info.name,type_name:info.type_name})
          })
        }
        // 绑定
        if(key === '2'){
          if(info['type_name'] !== 4){
            _this.bindPop = true;
            _this.bindTitle = `绑定${_this.typeNameText[info['type_name']]}(${_this.labelsInfo.name})`;
            _this.getBindDataList();
          }else {
            _this.bindHouseTitle = `绑定住户(${_this.labelsInfo.name})`
            _this.bindUserModal = true;
            _this.$nextTick(() => {
              _this.bindUserForm.setFieldsValue({id:info.id});
            })
          }
        }
        // 查看绑定住户列表
        if(key === '2.5') _this.$router.push({name:'data_labels_bindList',params:{id:info.id}})
        // 删除
        if(key === '3'){
          _this.$confirm({
            title: `确定要将标签\"${info.name}\"删除？`,
            onOk() {
              return new Promise((resolve, reject) => {
                _this.axios({
                  method:'post',
                  url:'/labels/del',
                  data:{token:_this.token,id:info.id},
                }).then(res => {
                  if(res.code === 0){
                    _this.$message.success(res.msg,2);
                    _this.$refs.table.refresh();
                    resolve();
                  }else reject(res.msg);
                }).catch(err => {
                  _this.$message.error('服务器发生错误...',2);
                })
              }).catch((msg) => _this.$message.error(msg,2));
            },
            onCancel() {},
          });
        }
      },
      // 获取绑定数据
      getBindDataList() {
        this.axios({
          method:'post',
          url:'/labels/getBindData',
          data:{token:this.token,id:this.labelsInfo.id}
        }).then(res => {
          this.bindDataLoading = false;
          this.bindDataList = res.data.list;
          this.hasBind = res.data.bind;
          this.$nextTick(() => {
            this.bingdIds = res.data.bind;
          });
        }).catch(err => {
          this.$message.error('服务器发生错误...',2);
        })
      },
      // 获取小区列表
      getCommunity() {
        this.axios({
          method:'post',
          url:'/parking/getAllCommunityList',
          data:{token:this.token}
        }).then(res => {
          if(res.code === 0){
            this.communityList = res.data;
          }else this.$message.warning(res.msg);
        }).catch(err => {
          this.$message.error('服务器发生错误...');
        })
      },
      // 获取绑定住户列表
      getBindUserList(value) {
        let bd_info_id = this.bindUserForm.getFieldValue('bd_info_id');
        if(this.$common.isEmpty(bd_info_id)) {
          this.$message.warning('请先选择所属小区')
          return false
        }
        if (value && value.length > 1) {
          this.fetching = true;
          this.axios({
            method: "post",
            url: "/labels/getBindUserList",
            data: { id: this.labelsInfo.id, bd_info_id, token: this.token,text:value }
          }).then(res => {
            this.bindUserList = res.data;
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          }).finally(() => {
            this.fetching = false;
          })
        }else this.bindUserList = [];
      },
      // 提交绑定住户
      bindUserSubmit(e) {
        e.preventDefault();
        this.bindUserForm.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          Object.assign(values,{token:this.token});
          this.bindUserModalLoading = true;
          this.axios({
            method: 'post',
            url: '/labels/bindUser',
            data: values
          }).then(res => {
            if (res.code == 0) {
              this.$message.success('绑定成功', 1)
              this.bindUserModal = false;
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2);
          }).finally(() => {
            this.bindUserModalLoading = false;
          })
        })
      }
    },
    watch:{
      bindPop(val) {
        if(!val) {
          this.bindDataLoading = !val;
          this.bingdIds = [];
          this.hasBind = [];
          this.bindDataList = [];
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
    .content-head{
      display: flex;
      align-items: center;
      .content-head-title{
        display: inline-block;
        flex: 1 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .content-head-extra{
        float: right;
      }
    }
  }
</style>